import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution56 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals,(a,b)->a[0]==b[0]?b[1]-a[1]:a[0]-b[0]);
        int cur=0;
        List<int[]> list=new ArrayList<>();
        while (cur<intervals.length){
            int l=intervals[cur][0];
            int r=intervals[cur][1];
            while (cur+1<intervals.length && intervals[cur+1][0]<=r){
                r=Math.max(intervals[cur+1][1],r);
                cur++;
            }
            cur++;
            list.add(new int[]{l,r});
        }
        int[][] ans=new int[list.size()][2];
        for (int i=0;i<list.size();i++){
            ans[i]=list.get(i);
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(new Solution56().merge(new int[][]{{1, 3}, {2, 6}, {8, 10}, {15, 18}})));
    }
}
